
import 'package:flutter/material.dart';

//数字红点
class BadgeTab extends StatefulWidget {
  @override
  _BadgeTabState createState() => _BadgeTabState();
}

class _BadgeTabState extends State {
  final List<Widget> tabs = [
    _buildTab(icon: Icons.home, badgeCount: 5),
    _buildTab(icon: Icons.mail, badgeCount: 0),
    _buildTab(icon: Icons.person, badgeCount: 8),
  ];

  static Widget _buildTab({required IconData icon, required int badgeCount}) {
    return Stack(
      children: [
        Tab(
          icon: Icon(icon),
        ),
        Visibility(
          visible: badgeCount > 0,
          child: Positioned(
            top: 0,
            right: 0,
            child: Container(
              padding: EdgeInsets.all(1),
              decoration: BoxDecoration(
                color: Colors.red,
                borderRadius: BorderRadius.circular(10),
              ),
              constraints: BoxConstraints(
                minWidth: 18,
                minHeight: 18,
              ),
              child: Text(
                '$badgeCount',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                ),
                textAlign: TextAlign.center,
              ),
            ),
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: tabs.length,
      child: Scaffold(
        appBar: AppBar(
          title: Text('Complex Tab Demo'),
          bottom: TabBar(
            tabs: tabs,
            isScrollable: true,
            indicatorColor: Colors.transparent,
            onTap: (index) {
              setState(() {});
            },
          ),
        ),
        body: TabBarView(
          children: tabs.map((Widget widget) {
            return Center(child: widget);
          }).toList(),
        ),
      ),
    );
  }
}
